package com.coffee.socketio;


import com.coffee.concurrent.ExecutorConfigManager;
import com.coffee.concurrent.CoffeeDisruptor;
import com.coffee.concurrent.CoffeeDisruptorPool;
import com.coffee.concurrent.ThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;

/**
 * Manager of processors 处理器管理类<br>
 * Maintains the relationship between command and command processor through command code.
 *
 * @author songkui
 * @version   v 0.1 Sept 6, 2019 2:49:47  $
 */
@Slf4j
public class CoffeeSocketioExecutor {

    private CoffeeDisruptorPool executorPool;
    private ExecutorService defaultExecutor;

    private int minPoolSize = ExecutorConfigManager.default_tp_min_size();


    private int maxPoolSize = ExecutorConfigManager.default_tp_max_size();

    private int queueSize = ExecutorConfigManager.default_tp_queue_size();

    private long keepAliveTime = ExecutorConfigManager.default_tp_keepalive_time();

    private CoffeeSocketioExecutor() {
        defaultExecutor = ThreadPool.buildThreadPool(minPoolSize, maxPoolSize, queueSize, keepAliveTime, "mocha-pool");
    }

    private static final class ProcessorManagerHolder {
        static final CoffeeSocketioExecutor processorManager = new CoffeeSocketioExecutor();
    }

    public static CoffeeSocketioExecutor getInstance() {
        return ProcessorManagerHolder.processorManager;
    }

    public void start() {
        executorPool = new CoffeeDisruptorPool(32, "coffee-socket");
        executorPool.start();
    }

    public CoffeeDisruptor getDisruptorByUserId(long userId) {
        int index = (int) (userId % executorPool.size());
        return executorPool.getByIndex(index);
    }
    public CoffeeDisruptor getDisruptor(int no) {
        return executorPool.getByBizNo(no);
    }

    public ExecutorService getDefaultExecutor() {
        return defaultExecutor;
    }

}